makeSets <- function(M,KEGGList = NULL,GOList = NULL,minGenes = 10,maxGenes  = 350,Ontology = "BP"){


filterSets <- function(sets,M,minGenes,maxGenes){
    setLengths <- lapply(sets,length)
 
    for(set in names(sets)){
        setLengths[set] <- length(intersect(sets[[set]],rownames(M)))
    }
    filteredSets <- vector("list",length = sum(unlist(setLengths) >= minGenes & unlist(setLengths) <= maxGenes))
    names(filteredSets) <- names(setLengths)[unlist(setLengths) >= minGenes & unlist(setLengths) <= maxGenes]
 
    for (set in names(filteredSets)){
        filteredSets[[set]] <- sets[[set]]
    } 
    return(filteredSets)
}




library(KEGG.db)
library(GO.db)


if(!is.null(KEGGList)){
    pathNames <- as.list(KEGGPATHID2NAME)
    uuNames <- names(KEGGList)
    names(uuNames) <- uuNames 

    for (pw in uuNames){
        uuNames[pw] <- paste(pw,pathNames[[pw]])
    } 

names(KEGGList) <- uuNames
}

if(!is.null(GOList)){
    gg <- as.list(GOTERM)
    setsNames <- names(GOList)
    ind <- 0
    for(GOID in names(GOList)){
        ind <- ind + 1
        setsNames[ind] <- paste(GOID,getGOTerm(GOID)[[1]])
         if(gg[[GOID]]@Ontology != Ontology){
             GOList[[GOID]] <- "Irrelevant"
         }
    } 
    names(GOList) <- setsNames
}

sets <- c(KEGGList,GOList)

sets <- filterSets(sets,M,minGenes,maxGenes)

return(sets)

}